package com.firewolf.struts.fileupload.actions;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.upload.FormFile;

import com.firewolf.struts.fileupload.forms.UserForm;
import com.firewolf.struts.fileupload.models.User;
import com.firewolf.struts.fileupload.service.UserService;
import com.firewolf.struts.fileupload.utils.FileUtil;

/**
 * 
 * @Description: 注册Action
 * @Author: 刘兴
 * @Date : 2016年8月26日
 * @package : com.firewolf.struts.fileupload.actions
 * @Java_Version : 1.7
 * @Version : 2016年8月26日下午5:52:08
 */
public class RegisterAction extends DispatchAction {

	/**
	 * @Description: 注册用户 @输入和输出示例： @思路：
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward register(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		UserForm userForm = (UserForm) form;
		String name = userForm.getName();
		FormFile file = userForm.getPhoto();// 获取文件
		int size = file.getFileSize();// 文件大小
		String fileName = file.getFileName();
		String newFileName = FileUtil.getNewFileName(fileName);

		// 获取文件要保存的目录，files为和WEB-INF同级的目录，下面获取的是部署到服务器后的文件绝对路径
		String foldPath = getServlet().getServletContext().getRealPath("/files");
		System.out.println(foldPath);
		String realPath = foldPath + "\\" + newFileName;
		InputStream is = file.getInputStream();// 获取文件输入流

		OutputStream os = new FileOutputStream(realPath);
		int len = 0;
		byte[] buf = new byte[1024];
		try {
			while ((len = is.read(buf)) > 0) {// 写文件
				os.write(buf);
			}
		} catch (Exception e) {

		} finally {
			if (is != null)
				is.close();
			if (os != null)
				os.close();
		}
		try {
			User user = new User();
			user.setName(name);
			user.setOrignPhoto(fileName);
			user.setNewPhoto(newFileName);
			UserService service = new UserService();
			service.addUser(user);
		} catch (Exception e) {
			e.printStackTrace();
			mapping.findForward("err");
		}

		return mapping.findForward("ok");
	}

	/**
	 * @Description: 显示用户 @输入和输出示例： @思路：
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward showUsers(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		UserService service = new UserService();
		ArrayList<User> users = service.getAllUsers();
		request.setAttribute("users", users);
		return mapping.findForward("show");
	}

}
